﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleChart.Kernel.Series;
using System.Data;

namespace SimpleChart.Kernel.Painter
{
    class ColumnSeriesPainter : SeriesPainterBase
    {
        public override void Draw(Graphics graphics, Chart chart, SeriesBase series, int width, int height)
        {
            decimal ceiling = ChartHelper.GetAxisYCeiling(chart.Data, chart.SeriesCollection, series.AxisType);
            var points = ChartHelper.GetPoints(chart.Data, 0f, (float)ceiling, series.AxisYMember, width, height);
            DrawColumns(graphics, points, series.Color, width, height);
            DrawValueLables(graphics, chart.Data, series.AxisYMember, points, series.Color);
        }

        private void DrawValueLables(Graphics graphics, DataTable data, string axisYMember, List<PointF> points, Color color)
        {
            Brush brush = new SolidBrush(color);
            string fontName = SystemFonts.DefaultFont.FontFamily.Name;
            Font font = new Font(fontName, 12, FontStyle.Bold);

            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            for (int i = 0; i < data.Rows.Count; i++)
            {
                string str = data.Rows[i][axisYMember].ToString();
                SizeF strSize = graphics.MeasureString(str, font);
                graphics.DrawString(str, font, brush, new RectangleF { X = points[i].X - strSize.Width / 2 , Y = points[i].Y - 20, Width = strSize.Width, Height = 20 }, format);
            }
        }

        private void DrawColumns(Graphics graphics, List<PointF> points, Color color, int width, int height)
        {
            float columnWidth = (width - PainterParameters.MARGIN * 2 - PainterParameters.AXIS_Y_WIDHT * 2) / (float)points.Count / 2;

            foreach (var point in points)
            {
                graphics.FillRectangle(new SolidBrush(color),
                    new RectangleF
                    {
                        X = (point.X - columnWidth / 2),
                        Y = point.Y,
                        Width = columnWidth,
                        Height = height - PainterParameters.MARGIN - PainterParameters.AXIS_X_HEIGHT - PainterParameters.LEGEND_HEIGHT - point.Y
                    });
            }
        }
    }
}
